﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;

namespace PageAdmin.Utils
{
    /// <summary>
    /// 基础帮助类
    /// </summary>
    public class StringHelper
    {
        static object _lock = new object();
        static int count = 1;
        #region 判断方法，如是否数字，是否字符串等

        /// <summary>
        /// 通用正则验证
        /// </summary>
        /// <param name="input"></param>
        /// <param name="pattern"></param>
        /// <returns></returns>
        public static bool IsMatch(string input, string pattern)
        {
            return IsMatch(input, pattern, RegexOptions.IgnoreCase);
        }

        /// <summary>
        /// 通用正则验证，可自定义验证RegexOptions
        /// </summary>
        /// <param name="input">输入的字符串</param>
        /// <param name="pattern">模式字符串</param>
        /// <param name="options">筛选条件</param>
        public static bool IsMatch(string input, string pattern, RegexOptions options)
        {
            return Regex.IsMatch(input, pattern, options);
        }

        /// <summary>
        /// 是否是字母和数字和下划线组合
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>

        public static bool IsStr(string str) //字母或下划线组合
        {
            if (string.IsNullOrEmpty(str)) { return false; }
            string str1 = "abcdefghijklmnopqrstuvwxyz0123456789_";
            string str2 = str.ToLower();
            for (int i = 0; i < str2.Length; i++)
            {
                if (str1.IndexOf(str2[i]) == -1)
                {
                    return false;
                }
            }
            return true;
        }

        /// <summary>
        /// 是否是Decimal
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IsDecimal(string str)
        {
            if (string.IsNullOrEmpty(str)) { return false; }
            Decimal rv = 0;
            if (Decimal.TryParse(str, out rv))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 是否是double
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IsDouble(string str)
        {
            if (string.IsNullOrEmpty(str)) { return false; }
            double rv = 0;
            if (double.TryParse(str, out rv))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 是否是float
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IsFloat(string str)
        {
            if (string.IsNullOrEmpty(str)) { return false; }
            float rv = 0;
            if (float.TryParse(str, out rv))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 是否是int
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>

        public static bool IsInt(string str)
        {
            if (string.IsNullOrEmpty(str)) { return false; }
            int rv = 0;
            if (int.TryParse(str, out rv))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 否是int64
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IsLong(string str)
        {
            if (string.IsNullOrEmpty(str)) { return false; }
            long rv = 0;
            if (long.TryParse(str, out rv))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 否是int16
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IsShort(string str)
        {
            if (string.IsNullOrEmpty(str)) { return false; }
            short rv = 0;
            if (short.TryParse(str, out rv))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 是否是byte
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IsByte(string str)
        {
            if (string.IsNullOrEmpty(str)) { return false; }
            byte rv = 0;
            if (byte.TryParse(str, out rv))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 是否全是数字
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>

        public static bool IsNum(string str)  //是否全是数字
        {
            if (string.IsNullOrEmpty(str)) { return false; }
            System.Text.ASCIIEncoding ascii = new System.Text.ASCIIEncoding();
            byte[] bytestr = ascii.GetBytes(str);
            foreach (byte c in bytestr)
            {
                if (c < 48 || c > 57)
                {
                    return false;
                }
            }
            return true;
        }


        /// <summary>
        /// 是否是日期格式
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>

        public static bool IsDate(string str) //是否是日期格式
        {
            if (string.IsNullOrEmpty(str)) { return false; }
            if (str.Length < 8) { return false; }
            if (!IsInt(str.Substring(0, 4))) { return false; }
            int rn = 0;//是否闰年
            int year = int.Parse(str.Substring(0, 4));
            if ((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0)) { rn = 1; } else { rn = 0; }
            //str = str.Replace("/","-");
            if (rn == 1)
            {
                return IsMatch((str == null ? "" : str), @"^((((1[6-9]|[2-9]\d)\d{2})-(0?[13578]|1[02])-(0?[1-9]|[12]\d|3[01]))|(((1[6-9]|[2-9]\d)\d{2})-(0?[13456789]|1[012])-(0?[1-9]|[12]\d|30))|(((1[6-9]|[2-9]\d)\d{2})-0?2-(0?[1-9]|1\d|2[0-9]))|(((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))-0?2-29-))$");
            }
            else
            {
                return IsMatch((str == null ? "" : str), @"^((((1[6-9]|[2-9]\d)\d{2})-(0?[13578]|1[02])-(0?[1-9]|[12]\d|3[01]))|(((1[6-9]|[2-9]\d)\d{2})-(0?[13456789]|1[012])-(0?[1-9]|[12]\d|30))|(((1[6-9]|[2-9]\d)\d{2})-0?2-(0?[1-9]|1\d|2[0-8]))|(((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))-0?2-29-))$");
            }
        }

        /// <summary>
        /// 是否是时间+日期格式
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IsDateTime(string str)
        {
            if (string.IsNullOrEmpty(str)) { return false; }
            DateTime rv;
            if (DateTime.TryParse(str, out rv))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 是否是时间
        /// </summary>
        /// <param name="strSource"></param>
        /// <returns></returns>
        public static bool IsTime(string strSource)
        {
            if (string.IsNullOrEmpty(strSource)) { return false; }
            return IsMatch(strSource, @"^((20|21|22|23|[0-1]?\d):[0-5]?\d:[0-5]?\d)$");
        }

        /// <summary>
        /// 是否是手机
        /// </summary>
        /// <param name="val"></param>
        /// <returns></returns>
        public static bool IsMobile(string val)
        {
            if (string.IsNullOrEmpty(val)) { return false; }
            return IsMatch(val, @"^1[123456789]\d{9}$");
        }

        /// <summary>
        /// 是否是邮箱
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IsEmail(string str) //是否是邮箱
        {
            if (string.IsNullOrEmpty(str)) { return false; }
            else
            {
                return IsMatch(str, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,6}|[0-9]{1,3})(\]?)$");
            }
        }

        /// <summary>
        /// 是否是用户名
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IsUserName(string str)
        {
            if (string.IsNullOrEmpty(str)) { return false; }
            Regex re = new Regex(@"[\u4e00-\u9fa5]+");
            str = re.Replace(str, "");
            if (str.Length == 0) { return true; }
            else { return IsStr(str); }
        }

        /// <summary>
        /// 是否是文件
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static bool IsFile(string filePath,bool includeHttpFile=false)
        {
            if (string.IsNullOrEmpty(filePath))
            {
                return false;
            }
            if (includeHttpFile)
            {
                filePath = filePath.ToLower();
                if (filePath.StartsWith("http://") || filePath.StartsWith("https://") || filePath.StartsWith("ftp://"))
                {
                    filePath = filePath.Replace("http://", "").Replace("https://", "").Replace("ftp://", "");
                    filePath = filePath.Substring(filePath.IndexOf("/"));//获取后面的路径
                }
            }
            string[] Astr = filePath.Split('.');
            if (Astr.Length != 2)
            {
                return false;
            }
            else
            {
                if (!IsStr(Astr[1]))
                {
                    return false;
                }
                else if (Astr[0].Length < 0 || Astr[1].Length < 3 || Astr[1].Length > 4)
                {
                    return false;
                }
            }
            return true;
        }

        /// <summary>
        /// 是否是url地址,可包含路径
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static bool IsUrl(string url)
        {
            if (string.IsNullOrEmpty(url)) { return false; }
            if (!url.StartsWith("http://", StringComparison.OrdinalIgnoreCase) && !url.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
            {
                return false;
            }
            else
            {
                return true;
            }
        }



        /// <summary>
        /// 基于http请求，模拟出来的sessionId
        /// </summary>
        /// <param name="httpContextBase"></param>
        /// <returns></returns>
        public static string SessionId(HttpRequestBase request=null) //获取客户端唯一Id
        {
            var key = "SessionId";
            if (request == null)
            {
                var context = HttpContext.Current;
                if (context == null)
                {
                    return null;
                }
                request = new HttpRequestWrapper(context.Request);
            }
            var sessionId = request.Cookies[key]?.Value;
            if (string.IsNullOrEmpty(sessionId))
            {
                sessionId = request.Headers[key];
            }
            if (IsBase64(sessionId))
            {
                return sessionId;
            }
            else
            {
                sessionId =StringHelper.Base64Encode(StringHelper.NewGuid());
                CookieHelper.Add(key, sessionId);
            }
            return sessionId;
        }

        /// <summary>
        /// 获取服务器ip
        /// </summary>
        /// <returns></returns>
        public static string GetServerIP()
        {
            if (System.Web.HttpContext.Current == null) return "0.0.0.0";
            string serverIp = System.Web.HttpContext.Current.Request.ServerVariables["LOCAL_ADDR"];
            return serverIp;
        }

        /// <summary>
        /// 获取客户端ip
        /// </summary>
        /// <returns></returns>
        public static string GetClientIP()
        {
            if (HttpContext.Current == null) return "127.0.0.1";
            var request = HttpContext.Current.Request;
            string ip = request.Headers.Get("x-forwarded-for"); //由于Nginx反向代理后,header中会传递x-forwarded-for
            if (string.IsNullOrEmpty(ip) || string.Equals("unknown", ip, StringComparison.OrdinalIgnoreCase))
            {
                ip = request.Headers.Get("Proxy-Client-IP"); //TTP_CLIENT_IP ：有些代理服务器会加上此请求头。
            }
            if (string.IsNullOrEmpty(ip) || string.Equals("unknown", ip, StringComparison.OrdinalIgnoreCase))
            {
                ip = request.Headers.Get("WL-Proxy-Client-IP");//经过apache http服务器的请求
            }
            if (string.IsNullOrEmpty(ip) || string.Equals("unknown", ip, StringComparison.OrdinalIgnoreCase))
            {
                ip = request.Headers.Get("HTTP_CLIENT_IP"); //代理服务器 IP 
            }
            if (string.IsNullOrEmpty(ip) || string.Equals("unknown", ip, StringComparison.OrdinalIgnoreCase))
            {
                ip = request.Headers.Get("HTTP_X_FORWARDED_FOR");
            }
            if (string.IsNullOrEmpty(ip) || string.Equals("unknown", ip, StringComparison.OrdinalIgnoreCase))
            {
                ip = request.UserHostAddress;
            }
            if (!string.IsNullOrEmpty(ip) && ip.Contains(","))  //如果存在多个反向代理，获得的IP是一个用逗号分隔的IP集合，取第一个
            {
                ip = ip.Split(',')[0];
            }
            if (!StringHelper.IsIp(ip))
            {
                ip = "Unknown";
            }
            return ip;
        }


        [Obsolete("请使用GetClientIP")]
        /// <summary>
        /// 获取客户端ip
        /// </summary>
        /// <returns></returns>
        public static string GetIP()
        {
            return GetClientIP();
        }

        /// <summary>
        /// 检测ip是否合法，支持ipv4和ipv6
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public static bool IsIp(string ip)
        {
            IPAddress address;
            if (IPAddress.TryParse(ip,out address))
            {
                return true;
                //switch (address.AddressFamily)
                //{
                //    case System.Net.Sockets.AddressFamily.InterNetwork: //ipv4
                //        break;
                //    case System.Net.Sockets.AddressFamily.InterNetworkV6: //ipv6
                //        break;
                //    default:
                //        break;
                //}
            }
            else
            {
                return false;
            }
        }


        /// <summary>
        /// 检查是否是正确版本,格式必须是1.0.0，1.0.1类似
        /// </summary>
        /// <param name="version"></param>
        /// <returns></returns>
        public static bool IsVersion(string version)
        {
            if (string.IsNullOrEmpty(version))
            {
                return false;
            }
            string[] arrVersion = version.Split('.');
            if (arrVersion.Length < 1)
            {
                return false;
            }
            foreach (var item in arrVersion)
            {
                if (!IsInt(item))
                {
                    return false;
                }
            }
            return true;
        }

        #endregion



        /// <summary>
        /// html编码,只对左引号（“），左括号（（），and符合（&）等转换为等效字符，如果仅仅是担心输出HTML代码和JS方面的安全，可以使用HtmlAttributeEncode 方法，效率更高
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public static string HtmlAttributeEncode(string content)
        {
            return HttpUtility.HtmlAttributeEncode(content);
        }


        /// <summary>
        /// html编码，完全编码
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public static string HtmlEncode(string content)
        {
            return HttpUtility.HtmlEncode(content);
        }

        /// <summary>
        /// html解码
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public static string HtmlDecode(string content)
        {
            return HttpUtility.HtmlDecode(content);
        }

        #region 对字符串进行转换或处理的通用方法
        /// <summary>
        /// 格式化字符串，值类型涉及装箱拆箱操作
        /// </summary>
        /// <typeparam name="Ttype"></typeparam>
        /// <param name="obj"></param>
        /// <param name="nullString">obj为null时的字符串</param>
        /// <returns></returns>
        public static Ttype Format<Ttype>(object obj, string nullString = "")
        {
            return (Ttype)Format(obj, typeof(Ttype), nullString);
        }

        /// <summary>
        /// 格式化字符串，值类型涉及装箱拆箱操作
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="FormatType"></param>
        /// <param name="nullString"></param>
        /// <returns></returns>
        public static object Format(object obj, Type FormatType, string nullString = "")
        {
            object rv;
            string str;
            if (obj == null)
            {
                str = nullString;
            }
            else
            {
                str = obj.ToString();
            }
            if (FormatType == typeof(string))
            {
                if (str == null)
                {
                    str = nullString;
                }
                rv = str;
            }
            else if (FormatType == typeof(float))
            {
                if (!IsFloat(str))
                {
                    rv = 0;
                }
                else
                {
                    rv = float.Parse(str);
                }
            }
            else if (FormatType == typeof(double))
            {
                if (!IsDouble(str))
                {
                    rv = 0;
                }
                else
                {
                    rv = double.Parse(str);
                }
            }
            else if (FormatType == typeof(int) || FormatType.BaseType == typeof(Enum))
            {
                if (!IsInt(str))
                {
                    rv = 0;
                }
                else
                {
                    rv = int.Parse(str);
                }
            }
            else if (FormatType == typeof(long))
            {
                if (!IsLong(str))
                {
                    rv = (long)0;
                }
                else
                {
                    rv = Int64.Parse(str);
                }
            }
            else if (FormatType == typeof(short))
            {
                if (!IsShort(str))
                {
                    rv = (short)0;
                }
                else
                {
                    rv = Int16.Parse(str);
                }
            }
            else if (FormatType == typeof(byte))
            {
                if (!IsByte(str))
                {
                    rv = (byte)0;
                }
                else
                {
                    rv = byte.Parse(str);
                }
            }
            else if (FormatType == typeof(sbyte))
            {
                if (!IsByte(str))
                {
                    rv = (sbyte)0;
                }
                else
                {
                    rv = sbyte.Parse(str);
                }
            }
            else if (FormatType == typeof(decimal))
            {
                if (!IsDecimal(str))
                {
                    rv = (decimal)0;
                }
                else
                {
                    rv = decimal.Parse(str);
                }
            }
            else if (FormatType == typeof(DateTime))
            {
                if (!IsDateTime(str))
                {
                    rv = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                }
                else
                {
                    rv = DateTime.Parse(str);
                }
            }
            else if (FormatType == typeof(bool))
            {
                if (str.Equals("1"))
                {
                    rv = true;
                }
                else if (str.Equals("true", StringComparison.OrdinalIgnoreCase))
                {
                    rv = true;
                }
                else
                {
                    rv = false;
                }
            }
            else
            {
                rv = obj;
            }
            return rv;
        }

        /// <summary>
        /// 根据字符串转为对应数据类型（system.Type)
        /// </summary>
        /// <param name="valueType"></param>
        /// <returns></returns>
        public static Type TransformValueType(string valueType)
        {
            Type type = typeof(string);
            switch (valueType.ToLower())
            {
                case "decimal":
                    type = typeof(decimal);
                    break;

                case "double":
                    type = typeof(double);
                    break;

                case "float":
                case "single":
                    type = typeof(float);
                    break;

                case "int64":
                case "bigint":
                case "long":
                    type = typeof(long);
                    break;

                case "int32":
                case "int":
                    type = typeof(int);
                    break;

                case "smallint":
                case "int16":
                case "short":
                    type = typeof(short);
                    break;

                case "byte":
                case "tinyint":
                    type = typeof(byte);
                    break;

                case "date":
                case "datetime":
                    type = typeof(DateTime);
                    break;
            }
            return type;
        }


        /// <summary>
        /// 过滤一组重复值的逗号隔开的字符串
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="str"></param>
        /// <param name="removeKey">要去除的关键词</param>
        /// <param name="deleteRepeat"></param>
        /// <returns></returns>
        public static string Unique<T>(string str, string removeKey = "", bool deleteRepeat = true)
        {
            if (string.IsNullOrEmpty(str)) { return ""; }
            if (removeKey == null)
            {
                removeKey = "";
            }
            string[] Astr = str.Split(',');
            List<string> list = new List<string>();
            for (int i = 0; i < Astr.Length; i++)
            {
                var item = Astr[i];
                if (item.Equals(removeKey, StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }
                if (string.IsNullOrEmpty(item.ToString())) { continue; }
                switch (typeof(T).Name.ToLower())
                {
                    case "int32":
                    case "int":
                        if (!IsInt(item))
                        {
                            continue;
                        }
                        break;

                    case "float":
                        if (!IsFloat(item))
                        {
                            continue;
                        }
                        break;
                    case "byte":
                        if (!IsByte(item))
                        {
                            continue;
                        }
                        break;
                }
                if (deleteRepeat && list.Contains(item))//判断数组值是否已经存在 
                {
                    continue;
                }
                list.Add(item);
            }
            return string.Join(",", list);
        }



        /// <summary>
        /// 获取字符串长度，中文是2个字符
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static int Length(string str)
        {
            if (string.IsNullOrWhiteSpace(str))
            {
                return 0;
            }
            var j = 0;
            var ce = str.GetEnumerator();
            while (ce.MoveNext())
            {
                j += (ce.Current > 0 && ce.Current < 255) ? 1 : 2;
            }
            return j;
        }


        /// <summary>
        /// 数组之间进行连接
        /// </summary>
        /// <param name="paths"></param>
        /// <param name="isFilePath"></param>
        /// <returns></returns>
        public static string Combine(params string[] paths)
        {
            if (paths.Length == 0)
            {
                throw new ArgumentException("please input path");
            }
            else
            {
                StringBuilder builder = new StringBuilder();
                string spliter = "/";
                string firstPath = paths[0];

                if (firstPath.StartsWith("ftp://", StringComparison.OrdinalIgnoreCase) || firstPath.StartsWith("http://", StringComparison.OrdinalIgnoreCase) || firstPath.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
                {
                    spliter = "/";
                }
                else if (firstPath.Contains(":"))
                {
                    spliter = "\\";
                }

                if (!firstPath.EndsWith(spliter))
                {
                    firstPath = firstPath + spliter;
                }
                builder.Append(firstPath);

                for (int i = 1; i < paths.Length; i++)
                {
                    string nextPath = paths[i];
                    if (nextPath.StartsWith("/") || nextPath.StartsWith("\\"))
                    {
                        nextPath = nextPath.Substring(1);
                    }

                    if (i != paths.Length - 1)//not the last one
                    {
                        if (nextPath.EndsWith("/") || nextPath.EndsWith("\\"))
                        {
                            nextPath = nextPath.Substring(0, nextPath.Length - 1) + spliter;
                        }
                        else
                        {
                            nextPath = nextPath + spliter;
                        }
                    }
                    builder.Append(nextPath);
                }

                return builder.ToString();
            }
        }


        /// <summary>
        /// 截取执行的字节长度
        /// </summary>
        /// <param name="str"></param>
        /// <param name="length"></param>
        /// <param name="byByte">是否按字节长度截取</param>
        /// <returns></returns>
        public static string SubString(string str,int length,bool byByte=false)
        {
            var result = str;
            if (byByte)
            {
                int j = 0, k = 0;
                var ce = str.GetEnumerator();
                while (ce.MoveNext())
                {
                    j += (ce.Current > 0 && ce.Current < 255) ? 1 : 2;
                    if (j <= length)
                    {
                        k++;
                    }
                    else
                    {
                        result = str.Substring(0, k);
                        break;
                    }
                }
            }
            else
            {
                if(length<str.Length)
                {
                    result = str.Substring(0, length);
                }
            }
            return result;
        }

        /// <summary>
        /// 截取到最后一个字符串出现的位置
        /// </summary>
        /// <param name="str"></param>
        /// <param name="strChar"></param>
        /// <returns></returns>
        public static string SubString(string str, string strChar)
        {
            return str.Substring(0, str.LastIndexOf(strChar));
        }

        /// <summary>
        /// 第一个字符大写
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string FirstCharUpper(string str)
        {
            if (!string.IsNullOrEmpty(str))
            {
                if (str.Length > 1)
                {
                    str = str[0].ToString().ToUpper() + str.Substring(1, str.Length - 1);
                }
                else
                {
                    str = str.ToUpper();
                }
            }
            return str;
        }

        /// <summary>
        /// 格式化域名为http://www.pageadmin.net格式，或www.pageadmin.net
        /// </summary>
        /// <param name="domain"></param>
        /// <param name="hasHttpPrefix">是否需要加http://或https://前缀</param>
        /// <returns></returns>
        public static string DomainFormat(string domain, bool hasHttpPrefix = true)
        {
            string httpPrefix = "http://";
            if (string.IsNullOrEmpty(domain))
            {
                return "";
            }
            domain = domain.ToLower();
            if (domain.StartsWith("http://", StringComparison.OrdinalIgnoreCase))
            {
                httpPrefix = "http://";
                domain = domain.Replace("http://", "");
            }
            else if (domain.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
            {
                httpPrefix = "https://";
                domain = domain.Replace("https://", "");
            }
            else if (domain.StartsWith("ftp://", StringComparison.OrdinalIgnoreCase))
            {
                httpPrefix = "ftp://";
                domain = domain.Replace("ftp://", "");
            }
            else if (domain.StartsWith("//", StringComparison.OrdinalIgnoreCase))
            {
                httpPrefix = "//";
                domain = domain.Replace("//", "");
            }
            domain = domain.Replace(@"\", "/");
            if (domain.IndexOf("/") > 0)
            {
                domain = domain.Substring(0, domain.IndexOf("/"));
            }
            if (hasHttpPrefix)
            {
                return httpPrefix + domain;
            }
            else
            {
                return domain;
            }
        }

        /// <summary>
        /// 主要格式化in 参数
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="values"></param>
        /// <returns></returns>
        public static string SqlFormat<T>(IEnumerable<string> values) //sql格式化，带模糊搜索过滤
        {
            List<string> list = new List<string>();
            foreach (string item in values)
            {
                if (item != null)
                {
                    var newValue = Format<T>(SqlFormat(item));
                    if (newValue.ToString() == item)
                    {
                        list.Add(item);
                    }
                }
            }
            return string.Join(",", list);
        }


        /// <summary>
        /// sql格式化,防止非法字符导致sql注入，正常使用建议采用参数化提交
        /// </summary>
        /// <param name="str"></param>
        /// <param name="isFuzzyQuery"></param>
        /// <returns></returns>

        public static string SqlFormat(string str, bool isFuzzyQuery = false)
        {
            if (string.IsNullOrEmpty(str)) { return string.Empty; }
            str = str.Replace("'", "''");
            if (isFuzzyQuery)
            {
                str = str.Replace("[]", "[[]]");
                str = str.Replace("[", "[[]");
                str = str.Replace("]", "[]]");
                str = str.Replace("_", "[_]");
                str = str.Replace("%", "[%]");
                str = str.Replace("^", "[^]");
            }
            return str;
        }

        /// <summary>
        /// html转换为为本
        /// </summary>
        /// <param name="strHtml"></param>
        /// <returns></returns>
        public static string HtmlToTxt(string strHtml)
        {
            string[] aryReg ={
            @"<script[^>]*?>.*?</script>",
            @"<(\/\s*)?!?((\w+:)?\w+)(\w+(\s*=?\s*(([""'])(\\[""'tbnr]|[^\7])*?\7|\w+)|.{0})|\s)*?(\/\s*)?>",
            @"([\r\n])[\s]+",
            @"&(quot|#34);",
            @"&(amp|#38);",
            @"&(lt|#60);",
            @"&(gt|#62);",
            @"&(nbsp|#160);",
            @"&(iexcl|#161);",
            @"&(cent|#162);",
            @"&(pound|#163);",
            @"&(copy|#169);",
            @"&#(\d+);",
            @"-->",
            @"<!--.*\n"
            };

            string newReg = aryReg[0];
            string strOutput = strHtml;
            for (int i = 0; i < aryReg.Length; i++)
            {
                Regex regex = new Regex(aryReg[i], RegexOptions.IgnoreCase);
                strOutput = regex.Replace(strOutput, string.Empty);
            }

            strOutput.Replace("<", "");
            strOutput.Replace(">", "");
            strOutput.Replace("\r\n", "");
            return strOutput;
        }


        /// <summary>
        /// 删除script脚本
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static string ClearScript(string text)
        {
            string pattern;

            if (text.Length == 0)
                return text;

            pattern = @"(?i)<script([^>])*>(\w|\W)*</script([^>])*>";
            text = Regex.Replace(text, pattern, String.Empty, RegexOptions.IgnoreCase);

            pattern = @"<script([^>])*>";
            text = Regex.Replace(text, pattern, String.Empty, RegexOptions.IgnoreCase);

            pattern = @"</script>";
            text = Regex.Replace(text, pattern, String.Empty, RegexOptions.IgnoreCase);

            return text;
        }

        /// <summary>
        /// ip转为数字，方便进行比较
        /// </summary>
        /// <param name="strIp"></param>
        /// <returns></returns>
        public static int IPtoNum(string strIp)
        {
            string[] temp = strIp.Split('.');
            return (int.Parse(temp[0])) * 256 * 256 * 256 + (int.Parse(temp[1])) * 256 * 256 * 256 + (int.Parse(temp[2])) * 256 * 256 * 256;
        }


        #endregion
        /// <summary>
        /// 生成guid
        /// </summary>
        /// <returns></returns>
        public static string NewGuid(string formmat = "N")
        {
            return Guid.NewGuid().ToString(formmat);
        }

        /// <summary>
        /// 生成一个唯一订单号
        /// </summary>
        /// <param name="prefix"></param>
        /// <returns></returns>
        public static string GetOrderId(string prefix = "")
        {
            lock (_lock)
            {
                if (count >= 1000)
                {
                    count = 1;
                }
                var number = prefix + DateTime.Now.ToString("yyyyMMddHHmmss") + count.ToString().PadLeft(3, '0');
                count++;
                return number;
            }
        }
        #region 各进制数间转换
        /// <summary>
        /// 实现各进制数间的转换。ConvertBase("15",10,16)表示将十进制数15转换为16进制的数。
        /// </summary>
        /// <param name="value">要转换的值,即原值</param>
        /// <param name="from">原值的进制,只能是2,8,10,16四个值。</param>
        /// <param name="to">要转换到的目标进制，只能是2,8,10,16四个值。</param>
        public static string ConvertBase(string value, int from, int to)
        {
            try
            {
                int intValue = Convert.ToInt32(value, from);  //先转成10进制
                string result = Convert.ToString(intValue, to);  //再转成目标进制
                if (to == 2)
                {
                    int resultLength = result.Length;  //获取二进制的长度
                    switch (resultLength)
                    {
                        case 7:
                            result = "0" + result;
                            break;
                        case 6:
                            result = "00" + result;
                            break;
                        case 5:
                            result = "000" + result;
                            break;
                        case 4:
                            result = "0000" + result;
                            break;
                        case 3:
                            result = "00000" + result;
                            break;
                    }
                }
                return result;
            }
            catch
            {
                return "0";
            }
        }
        #endregion


        #region Base64位加密解密
        public static bool IsBase64(string input)
        {
            try
            {
                Convert.FromBase64String(input);
                return true;
            }
            catch
            {
                return false;
            }
        }

        public static string Base64Encode(string text)
        {
            if (string.IsNullOrEmpty(text)) return string.Empty;
            var plainTextBytes = Encoding.UTF8.GetBytes(text);
            return Convert.ToBase64String(plainTextBytes);
        }

        public static string Base64Decode(string base64EncodedData)
        {
            if (!IsBase64(base64EncodedData))
            {
                return string.Empty;
            }
            var base64EncodedBytes = Convert.FromBase64String(base64EncodedData);
            return Encoding.UTF8.GetString(base64EncodedBytes);
        }
        #endregion


        #region 和byte[]相关的方法
        /// <summary>
        /// 使用指定字符集将string转换成byte[]素组
        /// </summary>
        /// <param name="text">要转换的字符串</param>
        /// <param name="encoding">字符编码</param>
        public static byte[] StringToBytes(string text, Encoding encoding)
        {
            return encoding.GetBytes(text);
        }

        /// <summary>
        /// 使用指定字符集将byte[]转换成string
        /// </summary>
        /// <param name="bytes">要转换的字节数组</param>
        /// <param name="encoding">字符编码</param>
        public static string BytesToString(byte[] bytes, Encoding encoding)
        {
            return encoding.GetString(bytes);
        }

        /// <summary>
        /// 将byte[]转换成int32
        /// </summary>
        /// <param name="data">需要转换成整数的byte数组</param>
        public static int BytesToInt(byte[] data)
        {
            //如果传入的字节数组长度小于4,则返回0
            if (data.Length < 4)
            {
                return 0;
            }

            //定义要返回的整数
            int num = 0;

            //如果传入的字节数组长度大于4,需要进行处理
            if (data.Length >= 4)
            {
                //创建一个临时缓冲区
                byte[] tempBuffer = new byte[4];

                //将传入的字节数组的前4个字节复制到临时缓冲区
                Buffer.BlockCopy(data, 0, tempBuffer, 0, 4);

                //将临时缓冲区的值转换成整数，并赋给num
                num = BitConverter.ToInt32(tempBuffer, 0);
            }

            //返回整数
            return num;
        }
        #endregion

        #region 和汉字有关的方法
        /// <summary>
        /// 获取汉字拼音首字母（可包含多个汉字）
        /// </summary>
        /// <Param name="strText"></Param>
        /// <returns></returns>
        public static string GetChineseSpell(string strText)
        {
            int len = strText.Length;
            string myStr = "";
            for (int i = 0; i < len; i++)
            {
                myStr += GetSpell(strText.Substring(i, 1));
            }
            return myStr;
        }

        /// <summary>
        /// 获取汉字的拼音
        /// </summary>
        /// <param name="cnChar"></param>
        /// <returns></returns>
        public static string GetSpell(string cnChar)
        {
            var arrCn = Encoding.Default.GetBytes(cnChar);
            if (arrCn.Length > 1)
            {
                int area = (short)arrCn[0];
                int pos = (short)arrCn[1];
                int code = (area << 8) + pos;
                int[] areacode = { 45217, 45253, 45761, 46318, 46826, 47010, 47297, 47614, 48119, 48119, 49062, 49324, 49896, 50371, 50614, 50622, 50906, 51387, 51446, 52218, 52698, 52698, 52698, 52980, 53689, 54481 };
                for (int i = 0; i < 26; i++)
                {
                    int max = 55290;
                    if (i != 25) max = areacode[i + 1];
                    if (areacode[i] <= code && code < max)
                    {
                        return Encoding.Default.GetString(new byte[] { (byte)(65 + i) });
                    }
                }
                return "*";
            }
            return cnChar;
        }

        /// <summary>
        /// 获取第一个汉字的首字母，只能输入汉字
        /// </summary>
        /// <Param name="c"></Param>
        /// <returns></returns>
        public static string GetInitial(string c)
        {
            byte[] array = new byte[2];
            array = System.Text.Encoding.Default.GetBytes(c);
            int i = (short)(array[0] - '\0') * 256 + ((short)(array[1] - '\0'));
            if (i < 0xB0A1) return "*";
            if (i < 0xB0C5) return "A";
            if (i < 0xB2C1) return "B";
            if (i < 0xB4EE) return "C";
            if (i < 0xB6EA) return "D";
            if (i < 0xB7A2) return "E";
            if (i < 0xB8C1) return "F";
            if (i < 0xB9FE) return "G";
            if (i < 0xBBF7) return "H";
            if (i < 0xBFA6) return "J";
            if (i < 0xC0AC) return "K";
            if (i < 0xC2E8) return "L";
            if (i < 0xC4C3) return "M";
            if (i < 0xC5B6) return "N";
            if (i < 0xC5BE) return "O";
            if (i < 0xC6DA) return "P";
            if (i < 0xC8BB) return "Q";
            if (i < 0xC8F6) return "R";
            if (i < 0xCBFA) return "S";
            if (i < 0xCDDA) return "T";
            if (i < 0xCEF4) return "W";
            if (i < 0xD1B9) return "X";
            if (i < 0xD4D1) return "Y";
            if (i < 0xD7FA) return "Z";
            return "*";
        }


        private static int[] _ChinesePinYinValue = new int[]
        {
                -20319,-20317,-20304,-20295,-20292,-20283,-20265,-20257,-20242,-20230,-20051,-20036,
                -20032,-20026,-20002,-19990,-19986,-19982,-19976,-19805,-19784,-19775,-19774,-19763,
                -19756,-19751,-19746,-19741,-19739,-19728,-19725,-19715,-19540,-19531,-19525,-19515,
                -19500,-19484,-19479,-19467,-19289,-19288,-19281,-19275,-19270,-19263,-19261,-19249,
                -19243,-19242,-19238,-19235,-19227,-19224,-19218,-19212,-19038,-19023,-19018,-19006,
                -19003,-18996,-18977,-18961,-18952,-18783,-18774,-18773,-18763,-18756,-18741,-18735,
                -18731,-18722,-18710,-18697,-18696,-18526,-18518,-18501,-18490,-18478,-18463,-18448,
                -18447,-18446,-18239,-18237,-18231,-18220,-18211,-18201,-18184,-18183, -18181,-18012,
                -17997,-17988,-17970,-17964,-17961,-17950,-17947,-17931,-17928,-17922,-17759,-17752,
                -17733,-17730,-17721,-17703,-17701,-17697,-17692,-17683,-17676,-17496,-17487,-17482,
                -17468,-17454,-17433,-17427,-17417,-17202,-17185,-16983,-16970,-16942,-16915,-16733,
                -16708,-16706,-16689,-16664,-16657,-16647,-16474,-16470,-16465,-16459,-16452,-16448,
                -16433,-16429,-16427,-16423,-16419,-16412,-16407,-16403,-16401,-16393,-16220,-16216,
                -16212,-16205,-16202,-16187,-16180,-16171,-16169,-16158,-16155,-15959,-15958,-15944,
                -15933,-15920,-15915,-15903,-15889,-15878,-15707,-15701,-15681,-15667,-15661,-15659,
                -15652,-15640,-15631,-15625,-15454,-15448,-15436,-15435,-15419,-15416,-15408,-15394,
                -15385,-15377,-15375,-15369,-15363,-15362,-15183,-15180,-15165,-15158,-15153,-15150,
                -15149,-15144,-15143,-15141,-15140,-15139,-15128,-15121,-15119,-15117,-15110,-15109,
                -14941,-14937,-14933,-14930,-14929,-14928,-14926,-14922,-14921,-14914,-14908,-14902,
                -14894,-14889,-14882,-14873,-14871,-14857,-14678,-14674,-14670,-14668,-14663,-14654,
                -14645,-14630,-14594,-14429,-14407,-14399,-14384,-14379,-14368,-14355,-14353,-14345,
                -14170,-14159,-14151,-14149,-14145,-14140,-14137,-14135,-14125,-14123,-14122,-14112,
                -14109,-14099,-14097,-14094,-14092,-14090,-14087,-14083,-13917,-13914,-13910,-13907,
                -13906,-13905,-13896,-13894,-13878,-13870,-13859,-13847,-13831,-13658,-13611,-13601,
                -13406,-13404,-13400,-13398,-13395,-13391,-13387,-13383,-13367,-13359,-13356,-13343,
                -13340,-13329,-13326,-13318,-13147,-13138,-13120,-13107,-13096,-13095,-13091,-13076,
                -13068,-13063,-13060,-12888,-12875,-12871,-12860,-12858,-12852,-12849,-12838,-12831,
                -12829,-12812,-12802,-12607,-12597,-12594,-12585,-12556,-12359,-12346,-12320,-12300,
                -12120,-12099,-12089,-12074,-12067,-12058,-12039,-11867,-11861,-11847,-11831,-11798,
                -11781,-11604,-11589,-11536,-11358,-11340,-11339,-11324,-11303,-11097,-11077,-11067,
                -11055,-11052,-11045,-11041,-11038,-11024,-11020,-11019,-11018,-11014,-10838,-10832,
                -10815,-10800,-10790,-10780,-10764,-10587,-10544,-10533,-10519,-10331,-10329,-10328,
                -10322,-10315,-10309,-10307,-10296,-10281,-10274,-10270,-10262,-10260,-10256,-10254
        };
        //定义拼音数组
        private static string[] _ChinesePinYin = new string[]
            {
                "A","Ai","An","Ang","Ao","Ba","Bai","Ban","Bang","Bao","Bei","Ben",
                "Beng","Bi","Bian","Biao","Bie","Bin","Bing","Bo","Bu","Ba","Cai","Can",
                "Cang","Cao","Ce","Ceng","Cha","Chai","Chan","Chang","Chao","Che","Chen","Cheng",
                "Chi","Chong","Chou","Chu","Chuai","Chuan","Chuang","Chui","Chun","Chuo","Ci","Cong",
                "Cou","Cu","Cuan","Cui","Cun","Cuo","Da","Dai","Dan","Dang","Dao","De",
                "Deng","Di","Dian","Diao","Die","Ding","Diu","Dong","Dou","Du","Duan","Dui",
                "Dun","Duo","E","En","Er","Fa","Fan","Fang","Fei","Fen","Feng","Fo",
                "Fou","Fu","Ga","Gai","Gan","Gang","Gao","Ge","Gei","Gen","Geng","Gong",
                "Gou","Gu","Gua","Guai","Guan","Guang","Gui","Gun","Guo","Ha","Hai","Han",
                "Hang","Hao","He","Hei","Hen","Heng","Hong","Hou","Hu","Hua","Huai","Huan",
                "Huang","Hui","Hun","Huo","Ji","Jia","Jian","Jiang","Jiao","Jie","Jin","Jing",
                "Jiong","Jiu","Ju","Juan","Jue","Jun","Ka","Kai","Kan","Kang","Kao","Ke",
                "Ken","Keng","Kong","Kou","Ku","Kua","Kuai","Kuan","Kuang","Kui","Kun","Kuo",
                "La","Lai","Lan","Lang","Lao","Le","Lei","Leng","Li","Lia","Lian","Liang",
                "Liao","Lie","Lin","Ling","Liu","Long","Lou","Lu","Lv","Luan","Lue","Lun",
                "Luo","Ma","Mai","Man","Mang","Mao","Me","Mei","Men","Meng","Mi","Mian",
                "Miao","Mie","Min","Ming","Miu","Mo","Mou","Mu","Na","Nai","Nan","Nang",
                "Nao","Ne","Nei","Nen","Neng","Ni","Nian","Niang","Niao","Nie","Nin","Ning",
                "Niu","Nong","Nu","Nv","Nuan","Nue","Nuo","O","Ou","Pa","Pai","Pan",
                "Pang","Pao","Pei","Pen","Peng","Pi","Pian","Piao","Pie","Pin","Ping","Po",
                "Pu","Qi","Qia","Qian","Qiang","Qiao","Qie","Qin","Qing","Qiong","Qiu","Qu",
                "Quan","Que","Qun","Ran","Rang","Rao","Re","Ren","Reng","Ri","Rong","Rou",
                "Ru","Ruan","Rui","Run","Ruo","Sa","Sai","San","Sang","Sao","Se","Sen",
                "Seng","Sha","Shai","Shan","Shang","Shao","She","Shen","Sheng","Shi","Shou","Shu",
                "Shua","Shuai","Shuan","Shuang","Shui","Shun","Shuo","Si","Song","Sou","Su","Suan",
                "Sui","Sun","Suo","Ta","Tai","Tan","Tang","Tao","Te","Teng","Ti","Tian",
                "Tiao","Tie","Ting","Tong","Tou","Tu","Tuan","Tui","Tun","Tuo","Wa","Wai",
                "Wan","Wang","Wei","Wen","Weng","Wo","Wu","Xi","Xia","Xian","Xiang","Xiao",
                "Xie","Xin","Xing","Xiong","Xiu","Xu","Xuan","Xue","Xun","Ya","Yan","Yang",
                "Yao","Ye","Yi","Yin","Ying","Yo","Yong","You","Yu","Yuan","Yue","Yun",
                "Za", "Zai","Zan","Zang","Zao","Ze","Zei","Zen","Zeng","Zha","Zhai","Zhan",
                "Zhang","Zhao","Zhe","Zhen","Zheng","Zhi","Zhong","Zhou","Zhu","Zhua","Zhuai","Zhuan",
                "Zhuang","Zhui","Zhun","Zhuo","Zi","Zong","Zou","Zu","Zuan","Zui","Zun","Zuo"
           };
        //建立一个convertCh方法用于将汉字转换成全拼的拼音，其中，参数代表汉字字符串，此方法的返回值是转换后的拼音字符串



        /// <summary>
        /// 汉字转换成全拼的拼音
        /// </summary>
        /// <param name="Chstr">汉字字符串</param>
        /// <returns>转换后的拼音字符串</returns>

        public static string ConvertChinese(string Chstr)
        {
            Regex reg = new Regex("^[\u4e00-\u9fa5]$");//验证是否输入汉字
            byte[] arr = new byte[2];
            string pystr = "";
            int asc = 0, M1 = 0, M2 = 0;
            char[] mChar = Chstr.ToCharArray();//获取汉字对应的字符数组
            for (int j = 0; j < mChar.Length; j++)
            {
                //如果输入的是汉字
                if (reg.IsMatch(mChar[j].ToString()))
                {
                    arr = System.Text.Encoding.Default.GetBytes(mChar[j].ToString());
                    M1 = (short)(arr[0]);
                    M2 = (short)(arr[1]);
                    asc = M1 * 256 + M2 - 65536;
                    if (asc > 0 && asc < 160)
                    {
                        pystr += mChar[j];
                    }
                    else
                    {
                        switch (asc)
                        {
                            case -9254:
                                pystr += "Zhen"; break;
                            case -8985:
                                pystr += "Qian"; break;
                            case -5463:
                                pystr += "Jia"; break;
                            case -8274:
                                pystr += "Ge"; break;
                            case -5448:
                                pystr += "Ga"; break;
                            case -5447:
                                pystr += "La"; break;
                            case -4649:
                                pystr += "Chen"; break;
                            case -5436:
                                pystr += "Mao"; break;
                            case -5213:
                                pystr += "Mao"; break;
                            case -3597:
                                pystr += "Die"; break;
                            case -5659:
                                pystr += "Tian"; break;
                            default:
                                for (int i = (_ChinesePinYinValue.Length - 1); i >= 0; i--)
                                {
                                    if (_ChinesePinYinValue[i] <= asc)//判断汉字的拼音区编码是否在指定范围内
                                    {
                                        pystr += _ChinesePinYin[i];//如果不超出范围则获取对应的拼音
                                        break;
                                    }
                                }
                                break;
                        }
                    }
                }
                else//如果不是汉字
                {
                    pystr += mChar[j].ToString();//如果不是汉字则返回
                }
            }
            return pystr;//返回获取到的汉字拼音
        }

        #endregion

        #region 历史方法不建议使用
        /// <summary>
        ///  过滤一组重复值的逗号隔开的字符串
        /// </summary>
        /// <param name="str"></param>
        /// <param name="removeKey"></param>
        /// <param name="deleteRepeat"></param>
        /// <returns></returns>
        [Obsolete]
        public static string Unique<T>(string str, string removeKey)
        {
            return Unique<T>(str, removeKey, false);
        }
        #endregion
    }
}
